package com.example.servicestest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import kotlinx.android.synthetic.main.activity_handle_test.*
import kotlin.concurrent.thread

class HandleTestActivity : AppCompatActivity() {

    val updateText = 1

    val handler = object : Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            //进行UI操作
            when(msg.what){
                updateText -> textView.text = "Nice to meet you!"
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_handle_test)

        button5.setOnClickListener {
            //开启线程的几种方式
            //1.继承Thread重写run 创建MyThread实例，调用start运行
            class MyThread : Thread(){
                override fun run(){
                    Log.d("HandleTest", "线程1")
                }
            }
            MyThread().start()
            //2.实现Runnable 传入Thread()参数，然后调用start启动
            class My2Thread : Runnable{
                override fun run() {
                    Log.d("HandleTest", "线程2")
                }
            }
            val my2Thread = My2Thread()
            Thread(my2Thread).start()
            //3.kotlin Lambda表达式 展开等同于2
            Thread{
                Log.d("HandleTest", "线程3")
            }.start()
            //4.kotlin提供的极简开启线程方法
            thread {
                Log.d("HandleTest", "线程4")
                val msg = Message()
                msg.what = 1
                handler.sendMessage(msg)
            }
        }
    }
}